<template>
	<div
	    class="pagination-container"
	    :style="{
	      'width': config.config.property.width+'px',
	      'background-color': config.config.property.bgColor,
	    }"
	  >
	    <div class="header">
	      <img src="./images/title.png" :style="{ 'width': '100%', 'height': '54px' }" />
	      <div
	        class="header-title"
	        :style="{ 'font-size': config.config.property.titleTextSize+'px', 'color': config.config.property.titleTextColor }"
	        >{{config.config.property.titleText }}{{ currentPage }}/{{ totalPages }}</div
	      >
	    </div>
	    <div class="content" v-if="showVisible">
	      <div
	        class="card"
	        v-for="(item, index) in paginatedItems"
	        :key="index"
	        :style="{ 'width': config.config.property.width - 20+'px', 'height': config.config.property.itemHight+'px' }"
	        @click="itemClick(item)"
	      >
	        <!-- <img
	          src="./images/item.png"
	          :style="{
	            'width': `${property.width - 20}px`,
	            'height': `${property.itemHight}px`,
	            'position': 'absolute',
	            'left': '11px',
	          }"
	        /> -->
	        <div
	          class="header-card"
	          :style="{ 'font-size': config.config.property.titleFontSize+'px', 'color': config.config.property.titleColor }"
	          >{{ item.title }}</div
	        >
	        <div class="content-right">
	          <div class="left">
	            <img src="./images/run.png" v-if="item.status == 'run'" :style="{ 'width': '69px' }" />
	            <img src="./images/stop.png" v-else :style="{ 'width': '69px' }" />
	          </div>
	          <div class="right">
	            <div :style="{ 'font-size': config.config.property.contentFontSize+'px', 'color': config.config.property.contentColor }"
	              >当日累计开机时长</div
	            >
	            <div :style="{ 'font-size': config.config.property.contentFontSize+'px', 'color': config.config.property.contentColor }"
	              ><span v-if="item.downtime1 > 0"
	                ><span class="height-light">{{ item.downtime1 }}</span>
	                <span :style="{ 'font-size': config.config.property.unitSize+'px', 'color': config.config.property.unitColor }"> 小时 </span>
	              </span>
	              <span class="height-light">{{ item.downtime2 }}</span>
	              <span :style="{ 'font-size': config.config.property.unitSize+'px', 'color':config.config.property.unitColor }"> 分钟 </span>
	            </div>
	            <div
	              :style="{
	                'font-size': config.config.property.contentFontSize+'px',
	                'color': config.config.property.contentColor,
	                'margin-top': '5px',
	              }"
	              >速度: <span class="height-light">{{ item.speed }}</span>
	              <span :style="{ 'font-size': config.config.property.unitSize+'px', 'color': config.config.property.unitColor }">
	                m/min
	              </span></div
	            >
	          </div>
	        </div>
	      </div>
	    </div>
	    <div class="pagination">
	      <div
	        class="dot"
	        v-for="(dot, index) in totalPages"
	        :key="index"
	        :class="{ active: currentPage === index + 1 }"
	        @click="goToPage(index + 1)"
	      ></div>
	    </div>
	  </div>
</template>
<script>
	import chartBase from '@/mixin/chart-base.js';
	import emitComponentBase from '@/mixin/emit-component-base.js';
	import dataModel from '@/models/panel-config-data.js';
	import {
		checkNegative
	} from '@/utils/util';
	import {
		mapState
	} from 'vuex';
	import config from './config/config';
	const itemsPerPage = 4;
	export default {
		name: 'Tunnelling',
		components: {

		},
		mixins: [chartBase, emitComponentBase],
		props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h', 'Item'],
		data() {
			return {
				isLoading: false,
				apiResult: [],
				paginatedItems: [],
				result: {},
				showVisible: false,
				isFull: false,
				items: [{
						title: '15201回风槽',
						downtime1: 4,
						downtime2: '25',
						speed: '8.3',
						status: 'red'
					},
					{
						title: '15201回风槽',
						downtime1: 0,
						downtime2: '55',
						speed: '8.3',
						status: 'green'
					},
					{
						title: '15201回风槽',
						downtime1: 0,
						downtime2: '35',
						speed: '8.3',
						status: 'red'
					},
					{
						title: '15201回风槽',
						downtime1: 4,
						downtime2: '25',
						speed: '8.3',
						status: 'green'
					},
				],
				currentPage: 1,

				totalPages: 0

			};
		},
		computed: {
			...mapState({}),
		},
		watch: {

		},
		created() {
			this.orgConfig = config;
			this.config = JSON.parse(JSON.stringify(this.orgConfig));
			this.chartId = `${this.widgetInstanceId}_01`;

		},
		mounted() {
			if (window.isLocalEnv) {
				this.loadWidget();
			}
			this.totalPages = Math.ceil(this.items.length / itemsPerPage)
			window.addEventListener('resize', function(event) {
				// 窗口大小变化时执行的代码
				var div = document.getElementById('my-container')
				var height = div.offsetHeight
				if (height > 200) {
					isFull.value = true
				} else {
					isFull.value = false
				}
			})
			// console.log(this.config)
		},
		methods: {

			// 初始加载时 以及 编排面更改配置时 触发
			loadWidget(pageStatus) {
				this.pageStatus = pageStatus;
				this.updateConfigProperty();
				this.updateConfigData();
				if (window.isLocalEnv || this.emitComponentStatus) {
					this.updateParams(pageStatus);
					if (!this.isRealTime) {
						this.debounceGetData();
					}
				}
				this.afterLoadWidget();
				this.checkNegative(this.apiResult);
			},

			// 接收xvue发来的实时数据
			handleRealTimeCommunication(realTimeData) {
				if (this.config.config.property.isDebounce && this.isStopRealData) {
					return;
				}

				const result = this.getResult(realTimeData);
				if (this.isNoData || this.autoRefreshIsSameRes(result)) {
					this.isLoading = false;
					return;
				}
				const {
					data,
					property
				} = this.config.config;

				// api请求，拿到数据
				if (data.dataSourceType !== 'xMinerRedisRealTime') {
					this.getCorrectParams(this.params, data.dataSourceType); // 参数存入xvue，导出数据时使用
				}
				// this.apiResult = result;
				// this.lastParams = null;
				// this.sendDataToConfig(result);
				// const convertedData = convertData(result, property);
				// if (convertedData === -1) {
				//   this.$message.error(this.$demoi18n('view.dataSourceTypeErr'));
				//   this.setDataException();
				//   return;
				// }
				// this.generateChart(convertedData);
				// this.isLoading = false;
			},
			acceptEvtMsg(paramters, key, obj) {
				this.checkUpdateParams(obj);
			},
			checkUpdateParams(obj) {
				// 检查下是否和本组件有关
				const _obj = obj || {};
				let oo = {}
				let flag = false;
				for (const key in _obj) {
					if (key.indexOf(EMIT_PARAMS_OBJ) > -1) {
						const o = _obj[key];
						if (o.eventKey) {
							const event = this.config.events.find(e => e.type === 'in' && e.key === o.eventKey);
							if (event) {
								flag = true;
								oo = o
							}
							break;
						}
					}
				}
				if (flag) {
					// 和本组件有关再执行组件接收到事件后的相关操作
					console.log('_obj', _obj)
					console.log('oo', oo)

					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const alarm_id = oo?.parameters[oo?.keys[0]]
					let param = {
						code: 'alarm_id',
						value: alarm_id
					}
					let paramOo = [param]

					// api请求，拿到数据
					const {
						data
					} = this.config.config
					this.isLoading = true
					const method = `getChartData${data.dataSourceType}`;
					const trueParams = this.getCorrectParams(this.params, data.dataSourceType);
					trueParams = {
						...trueParams,
						params: paramOo,
					};

					dataModel[method](trueParams, data)
						.then(result => {
							this.apiResult = result
							this.totalPages = Math.ceil(this.apiResult.length / itemsPerPage)
							this.apiResult.forEach((it) => {
								it.downtime1 = Math.floor(it.time / 60)
								it.downtime2 = it.time % 60
							})
							this.result = this.apiResult[0]
							const start = (this.currentPage - 1) * itemsPerPage
							this.paginatedItems = this.apiResult.slice(start, start + itemsPerPage)
							this.showVisible = true
							// 重置数据异常状态
							this.resetAbnormalType();
							this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
							if (this.autoRefreshIsSameRes(result)) {
								return;
							}

						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				}
			},
			getChartData() {
				const {
					data,
					property
				} = this.config.config;

				// 如果dataSourceType为静态数据,把数据放到Vuex，发出事件，然后退出
				if (data.dataSourceType === 'staticData') {
					this.apiResult = [{
							title: '15201回风槽',
							time: 163,
							speed: '8.3',
							status: 'stop',
							location: 44,
							direction: '2'
						},
						{
							title: '15201回风槽',
							time: 222,
							speed: '8.3',
							status: 'run',
							location: 88,
							direction: '2'
						},
						{
							title: '15201回风槽',
							time: 88,
							speed: '8.3',
							status: 'stop',
							location: 33,
							direction: '1'
						},
						{
							title: '15201回风槽',
							time: 73,
							speed: '8.3',
							status: 'run',
							location: 111,
							direction: '2'
						},
						{
							title: '15201回风槽',
							time: 23,
							speed: '8.3',
							status: 'stop',
							location: 55,
							direction: '1'
						},
					]
					this.totalPages = Math.ceil(this.apiResult.length / itemsPerPage)
					this.apiResult.forEach((it) => {
						it.downtime1 = Math.floor(it.time / 60)
						it.downtime2 = it.time % 60
					})
					this.result = this.apiResult[0]
					const start = (this.currentPage - 1) * itemsPerPage
					this.paginatedItems = this.apiResult.slice(start, start + itemsPerPage)
					this.showVisible = true
					// 重置数据异常状态
					this.resetAbnormalType();
					return;
				}

				// api请求，拿到数据
				if (data.dataSourceType) {
					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const method = `getChartData${data.dataSourceType}`;
					const params = this.getCorrectParams(this.params, data.dataSourceType);
					dataModel[method](params, data)
						.then(result => {
							this.apiResult = result
							this.totalPages = Math.ceil(this.apiResult.length / itemsPerPage)
							this.apiResult.forEach((it) => {
								it.downtime1 = Math.floor(it.time / 60)
								it.downtime2 = it.time % 60
							})
							this.result = this.apiResult[0]
							const start = (this.currentPage - 1) * itemsPerPage
							this.paginatedItems = this.apiResult.slice(start, start + itemsPerPage)
							this.showVisible = true
							// 重置数据异常状态
							this.resetAbnormalType();
							this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
							if (this.autoRefreshIsSameRes(result)) {
								return;
							}

						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				} else {
					// 如果在用户面，则给提示
					if (this.$route.name === 'userHomePage') {
						this.$message({
							message: this.$demoi18n('view.dataSourceTypeEmpty'),
							type: 'warning',
						});
					}
				}
			},
			goToPage(page) {
				const start = (page - 1) * itemsPerPage
				this.paginatedItems = this.apiResult.slice(start, start + itemsPerPage)
				this.currentPage = page
			},
			
			checkNegative,
			itemClick(params, data) {
				console.log(params)
			  this.chartClick(params, data);
			  if (params) {
			    this.sendAdvancedLinkagge({...params});
			  }
			},
			handleAsTooltip(filterRes) {
			  const { property } = this.config.config;
			  const convertedData = convertData(filterRes, property);
			  this.generateChart(convertedData);
			},
		},
	};
</script>
<style lang="less" scoped>
	// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
	@import '../../common/chart.less';
</style>
<style>
	/* 全局loading样式修改 */

	.chartMain .loading .el-loading-spinner .circular {
		width: 34px !important;
		height: 34px !important;
	}

	.chartMain .el-dialog__header {
		padding: 9px 20px 10px !important;
		background: #2a3352 !important;
		text-align: left;
		box-sizing: border-box;
		height: 50px;
		line-height: 32px;
	}

	.chartMain .el-dialog__title {
		text-align: left;
		/* font-size: 18px; */
		line-height: 18px !important;
		color: #b2d3fe !important;
	}

	.chartMain .el-dialog__body {
		padding: 10px 20px 30px 20px;
		background: #1a2032 !important;
		line-height: 24px;
		font-size: 14px;
	}

	.chartMain .el-dialog__headerbtn .el-dialog__close {
		color: #b2d3fe !important;
	}

	.chartMain .dialog-footer {
		text-align: right;
		margin-bottom: -14px;
		margin-right: 4px;
	}

	.chartMain .el-dialog__headerbtn {
		top: 15px;
		/* font-size: 18px; */
	}
</style>
<style scoped lang="less">
.rectangle {
  width: 200px; /* 八边形的宽度 */
  height: 20px; /* 八边形的高度 */
  background: linear-gradient(180deg, #6a11cb, #2575fc); /* 渐变背景 */
  clip-path: polygon(3% 0%, 97% 0%, 100% 25%, 100% 75%, 97% 100%, 3% 100%, 0% 75%, 0% 25%); /* 定义八边形的形状 */
  margin: 20px;
  position: relative; /* 位置相对，以便之后添加纹理 */
  overflow: hidden; /* 隐藏溢出部分 */
  box-shadow: inset 0 0 30px rgba(255, 255, 255, 0.2); /* 中间光影 */
}

.grid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('');
  background-size: 2px 2px; /* 纹理的大小 */
  opacity: 0.2; /* 设置纹理的透明度 */
}

.header {
  width: 100%;
  position: relative;
  .header-title {
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    line-height: 36px;
    font-weight: 600;
    text-align: center;
  }
}

.pagination-container {
  margin: auto;
  background-image: url('./images/back.png');
  background-size: cover; /* 或者使用 background-size: 100% 100%; */
  background-position: center; /* 可选，确保图片居中 */
  background-repeat: no-repeat; /* 可选，确保背景图不重复 */
  position: relative;
  height: 100%;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 11px 5px 0px 10px;
  margin-top: -20px;
  overflow-y: auto;
  height: calc(100% - 65px);
  // background-image: linear-gradient(to top, #3c4d6e, #091a3b);
  // border: 2px solid transparent; /* 透明边框 */
  // border-image: linear-gradient(to top, #3c4d6e, #091a3b) 1; /* 使用边框图像 */
}

.card {
  border-radius: 2px;
  color: white;
  text-align: center;
  cursor: pointer;
  background-image: url('./images/item.png');
  background-size: contain; /* 或者使用 background-size: 100% 100%; */
  background-position: center; /* 可选，确保图片居中 */
  background-repeat: no-repeat; /* 可选，确保背景图不重复 */
  // height: 88px;
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.header-card {
  font-weight: bold;
  line-height: 20px;
  text-align: center;
}

.content-right {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  .left {
    width: 40%;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    height: 60px;
  }
  .right {
    width: 60%;
    display: flex;
    flex-direction: column;
    padding: 2px;
    .height-light {
      color: #00f2ff;
      font-weight: 600;
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 0px 10px;
  position: absolute;
  width: 100%;
  bottom: 10px;
}

.dot {
  width: 10px;
  height: 2px;
  margin: 0 2px;
  background-color: #255e84;
  cursor: pointer;
  background-color: skyblue;
  transform: skew(30deg, 0); /* 倾斜30度，Y轴不倾斜 */
}

.active {
  background-color: #00ccff;
}

/* 整个滚动条 */
::-webkit-scrollbar {
  width: 4px; /* 滚动条的宽度 */
  height: 4px; /* 滚动条的高度 */
}

/* 滚动条上的滚动滑块 */
::-webkit-scrollbar-thumb {
  background-color: darkgrey; /* 滑块颜色 */
  border-radius: 2px; /* 滑块圆角 */
  border: 1px solid darkgrey; /* 滑块边框 */
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
  background: #f1f1f1; /* 轨道颜色 */
}
</style>